<template>
    <div class="container">
        <!-- 顶部统计信息 -->
        <div class="stats">
            <span>当前机构进度: {{ enrollmentStatisticsVal.hospitalCaseNum || '' }}</span>
            <span style="margin-left: 20px">总业务进度: {{ enrollmentStatisticsVal.totalCaseNum || '' }}</span>

            <!-- <span style="margin-left: 20px">访视期人数：0位</span>
      <span style="margin-left: 20px">已超窗人数：0位</span> -->
        </div>
        <advancedSearch v-model="openSearch" />
        <!-- 数据表格 -->
        <avue-crud :option="option" v-model:search="search" v-model:page="page" v-model="bringIntoForm"
            :table-loading="loading" :data="data" :before-open="beforeOpen" ref="crud" @row-update="rowUpdate"
            @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @on-load="onLoad" :row-style="rowStyle">

            <template #menu-left>
                <el-button type="primary" plain :icon="Plus" @click="handleBringIntoMenu(0)">新建病例</el-button>
              <el-button type="primary" plain :icon="DocumentChecked" @click="handleImport">导入病例</el-button>
            </template>

            <template #search-menu="{ row, size }">
                <!-- <el-button :size="size" type="primary" @click="handleAdvanceSearch">高级检索</el-button> -->
                <el-button :size="size" type="primary" @click="handleFollow">预约随访</el-button>
                <!-- <el-button :size="size" type="primary" @click="searchSubmit(row)">扫一扫</el-button>
        <el-button :size="size" type="primary" @click="handleSign">起始标识</el-button> -->
            </template>

            <template #name-header="{ column }">
                <el-tooltip class="box-item" effect="dark" :content="!isCutName ? '切换成全名' : '切换成姓名缩写'" placement="top">
                    <span style="color: #409eff;cursor: pointer" @click="cutName">{{ column.label }}</span>
                </el-tooltip>
            </template>

            <template #name="{ row }">
                <span style="color: #409eff; cursor: pointer" @click="handleUser(row)">{{ !isCutName ? row.name :
                    row.nameSx }}</span>
            </template>

            <template #progress="{ row }">
                <span>{{ row.collectionProgress }}<br />
                    <span @click="handlePresentCrf(row)" style="color:#409eff;cursor: pointer;">{{ row.presentCrf
                    }}</span>
                </span>
            </template>
            <!-- 自定义操作列 -->
            <template #menu="{ row }">
                <!-- <el-button text type="primary" @click="handleCustomData(row)">其他定制数据</el-button> -->
                <!-- <el-button text type="primary" @click="handleFile(row)">文件管理</el-button> -->
                <el-button text type="primary" @click="handleAppointment(row)">预约随访</el-button>
                <!-- <el-button text type="primary" @click="handleViewSample(row)">查看标本</el-button> -->
                <el-button text type="primary" @click="handleSock(1, row)" v-if="row.status == '1'">锁定</el-button>
                <el-button text type="primary" @click="handleSock(2, row)" v-if="row.status == '2'">恢复</el-button>
                <el-button text type="primary" @click="handleFall(row)" v-if="row.status == '1'">脱落</el-button>
                <el-button text type="primary" @click="handleFallDetail(row)" v-if="row.status == '3'">脱落原因</el-button>

                <el-button text type="primary" @click="handleEnd(row)" v-if="row.status != '4'">结束</el-button>

                <el-button text type="primary" @click="handleEnd(row)" v-if="row.status == '4'">结束签字</el-button>

                <el-button text type="primary" @click="handleComment(row)">评论</el-button>

                <el-button text type="primary" @click="handleRemark(row)">备注</el-button>

                <el-button text type="primary" danger @click="rowDel(row)" v-if="getTrialStatus == '1'">删除</el-button>
            </template>
        </avue-crud>
        <el-dialog v-model="isBringIntoDialog" :title="bringIntoDialogTitle" :width="bringIntoDialogWidth">
            <bringIntoAdd v-if="bringIntoMenuType === 0" @changeAddNewCase="changeAddNewCase" :selectTab="5" />
            <!-- @submit="allocationDialogSubmit" -->
            <!-- <avue-form :option="allocationDialogOption" v-model="allocationDialogForm"></avue-form> -->
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="isBringIntoDialog = false">关 闭</el-button>
                    <!-- <el-button type="primary" @click="dialogVisible = false"> 确 定 </el-button> -->
                </div>
            </template>
        </el-dialog>



      <el-dialog title="病例导入" append-to-body v-model="excelBox" width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
          <template #excelTemplate>
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>




        <userDialog v-model:userDialogVisible="userDialogVisible" :clickRow="clickRow" ref="userDialogRef" />
        <sampleView v-model:sampleDialog="sampleDialog" />
        <appointment ref="appointmentRef" v-model:appointmentDialog="appointmentDialog" />
        <el-dialog v-model="endDialog" title="样本结束" width="650">
            <!--      <el-table :data="tableData" border style="width: 100%" a>-->
            <!--        <el-table-column prop="doctor" label="所属医生" align="center" />-->
            <!--        <el-table-column prop="inputStatus" label="录入情况" align="center" />-->
            <!--        &lt;!&ndash; <el-table-column prop="DoubtStatus" label="质疑情况" align="center" /> &ndash;&gt;-->
            <!--      </el-table>-->
            <h3 v-if="endDialogVal.status != '4'">签字处</h3>
            <avue-sign ref="signRef" style="width: 100%" v-if="endDialogVal.status != '4'"></avue-sign>
            <img :src="endDialogVal.completedSign" style="width: 100%; background-color: #fff" alt=""
                v-if="endDialogVal.status == '4'" />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleOver" type="primary" v-if="endDialogVal.status != '4'">结束</el-button>
                    <el-button @click="endDialog = false"> 关闭 </el-button>
                </div>
            </template>
        </el-dialog>
        <calendar ref="calendarRef" />
    </div>
</template>

<script setup>
import {
    getList,
    getDetail,
    add,
    update,
    remove,
    npCrf,
    enrollmentStatistics,
    fallOff,
    completed,
    putFileBase64,
} from '@/api/clinicalcase/clinicalCase';
import calendar from '@/views/trial/components/calendar.vue';
import { getTrialDetail } from '@/api/trial/trial';
import { ref, reactive, nextTick, onMounted } from 'vue';
import { Plus,DocumentChecked } from '@element-plus/icons-vue';
import userDialog from './userDialog.vue';
import advancedSearch from './advancedSearch.vue';
import sampleView from './sampleView.vue';
import appointment from './appointment.vue';
import { $DialogForm } from '@smallwei/avue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import bringIntoAdd from '../bringIntoMenu/bringIntoAdd.vue';
const router = useRouter();
const { appContext } = getCurrentInstance();
const endDialog = ref(false);
const sampleDialog = ref(false);
const appointmentDialog = ref(false);

let calendarRef = ref(null);
let userDialogRef = ref(null);
const crud = ref();
const route = useRoute();
const routerQuery = ref({});
routerQuery.value = route.query;
const bringIntoForm = ref({});
const data = ref([]);
const query = ref({});
const search = ref({});
let loading = ref(false);
const page = ref({
    pageSize: 10,
    currentPage: 1,
    total: 0,
});
let signRef = ref(null);
const selectionList = ref([]);
const tableData = ref([]);


const excelBox = ref(false)
const excelForm = ref( {})
const excelOption = reactive({
    submitBtn: false,
    emptyBtn: false,
    column: [
    {
      label: '文件上传',
      prop: 'excelFile',
      type: 'upload',
      drag: true,
      loadText: '文件上传中，请稍等',
      span: 24,
      propsHttp: {
        res: 'data',
      },
      tip: '请上传 .xls,.xlsx,.xlsm 标准格式文件',
      action: '/blade-clinicalcase/clinicalCase/import',
    },
    /*{
      label: '模板下载',
      prop: 'excelTemplate',
      formslot: true,
      span: 24,
    },*/
  ],
})

// 表格配置
const option = reactive({
    border: true,
    index: true,
    indexWidth: 80,
    indexLabel: '编号',
    align: 'center',
    menuWidth: 280,
    //   searchIndex: 3,
    //   searchIcon: true,
    addBtn: false,
    height: 'auto',
    calcHeight: 40,
    searchSpan: 4,
    searchMenuPosition: 'right',
    searchMenuSpan: 8,
    search: false,
    editBtn: false,
    delBtn: false,
    labelWidth: 145,
    column: [
        {
            label: '姓名(切换)',
            prop: 'name',
            //   search: true,
            slot: true,
            width: 100,
            overHidden: true,
            display: false,
        },
        {
            label: '姓名',
            prop: 'name',
            search: true,
            slot: true,
            width: 100,
            overHidden: true,
            hide: true,
            rules: [
                {
                    required: true,
                    message: '请输入姓名',
                    trigger: 'blur',
                },
            ],
        },

        {
            label: '分组',
            prop: 'groupName',
            type: 'input',
            disabled: true,
            addDisplay: false,
        },
        {
            label: '手机号',
            prop: 'phone',
            search: true,
            hide: true,
            overHidden: true,
        },
       /* {
            label: '手机号是否认证',
            prop: 'radio',
            type: 'radio',
            border: true,
            dicData: [
                { label: '否', value: 0 },
                { label: '是', value: 1 },
            ],
            hide: true,
        },*/
        {
            label: '标识',
            prop: 'identification',
            search: false,
            overHidden: true,
            display: true,
        },
        {
            label: "出生日期",
            prop: "birthday",
            type: "date",
            format: 'YYYY年MM月DD日',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            hide: true,
             disabledDate (time) {
        return time.getTime() > Date.now();
      },
        },
        {
            label: '病例号',
            prop: 'caseNo',
            search: true,
            overHidden: true,
            display: false,
        },
        {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=clinical_case_status',
            props: {
                label: 'dictValue',
                value: 'dictKey',
            },
            display: false,
        },
        {
            label: '进度',
            prop: 'progress',
            slot: true,
            overHidden: true,
            display: false,
        },
        {
            label: '入组时间',
             prop: 'joinTime',
          // prop: 'createTime',
            overHidden: true,
            display: false,
             type: "date",
             format: 'YYYY-MM-DD',
             valueFormat: 'YYYY-MM-DD',
        },
        {
            label: '基准时间',
            prop: 'referenceTime',
            overHidden: true,
            type: "date",
            format: 'YYYY年MM月DD日',
            valueFormat: 'YYYY-MM-DD',
            display: false,
        },
        /*{
            label: '研究者',
            prop: 'researcherName',
            type: 'input',
            overHidden: true,
        },
        {
            label: '所属机构',
            prop: 'hospitalDeptName',
            type: 'input',
            overHidden: true,
        },*/
        {
            label: "住院号",
            prop: "zyh",
            type: "input",
            viewDisplay: false,
            search: true,
            rules: [
              {
                required: true,
                message: '请输入住院号',
                trigger: 'blur',
              },
            ],

        },
        {
            label: '评论',
            prop: 'comment',
            type: 'select',
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=group_manage_evaluate',
            props: {
                label: 'dictValue',
                value: 'dictKey',
            },
            filterable: true,
            overHidden: true,
            display: false,


        },
        {
            label: '备注',
            prop: 'remark',
            overHidden: true,
            display: false,
        },
    ],
});
const optionRemark = ref({
    span: 24,
    column: [
        {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            placeholder: '请输入备注',
        },
    ],
});
const optionComment = ref({
    span: 24,
    column: [
        {
            label: '评价',
            prop: 'comment',
            type: 'select',
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=group_manage_evaluate',
            props: {
                label: 'dictValue',
                value: 'dictKey',
            },
            filterable: true,
            overHidden: true,
            placeholder: '请选择评论',
        },
        {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            placeholder: '请输入备注',
        },
    ],
});
const optionSign = ref({
    span: 24,
    column: [
        {
            label: '起始标识',
            prop: 'sign',
            type: 'number',
            placeholder: '请输入起始标识',
        },
        {
            label: '',
            labelWidth: 20,
            type: 'title',
            prop: 'title1',
            span: 24,
            styles: {
                color: 'red',
                fontSize: '14px',
                marginTop: '-15px',
            },
        },
    ],
});
const optionFall = ref({
    span: 24,
    column: [
        {
            label: '脱落说明',
            prop: 'fallOffRemark',
            type: 'input',
            placeholder: '请输入脱落说明',
            rules: [
                {
                    required: true,
                    message: '请输入脱落说明',
                    trigger: 'blur',
                },
            ],
        },
        {
            label: '签字',
            prop: 'fallOffSign',
            type: 'input',
            placeholder: '执行人签字',
            rules: [
                {
                    required: true,
                    message: '请输入签字',
                    trigger: 'blur',
                },
            ],
        },
    ],
});

let getTrialStatus = ref('2');

const userDialogVisible = ref(false);
let clickRow = ref({});
let isBringIntoDialog = ref(false);
let bringIntoMenuType = ref(null);
let bringIntoDialogWidth = ref(500);
let sendAddNewCaseObj = ref(null);
/*
  type 0:新建病例
  type 1:唯一二维码
  type 2:配置信息
  type 3:高级配置
  type 4:自动编号
  type 5:导入数据
  type 6:导入病例
  type 7:姓名点击
  type 8:CRF查看点击
  type 9:入组采集
*/
const handleBringIntoMenu = (type, row = {}, index = null) => {
    bringIntoMenuType.value = type;
    const actions = {
        0: () => {
            isBringIntoDialog.value = true;
            bringIntoDialogTitle.value = '新建病例';
        },

    };

    // 执行对应的操作
    if (actions[type]) actions[type]();
};


const handleImport = () => {
  excelOption.column[0].action  = `/blade-clinicalcase/clinicalCase/import?trialId=`+routerQuery.value.trialId;
  excelBox.value = true;
}


const uploadAfter= (res, done, loading, column) => {
  excelBox.value = false;
  refreshChange();
  done();
}


const handleUser = row => {
    clickRow.value = row;
    userDialogVisible.value = true;
    row.status = getTrialStatus.value;
    nextTick(() => {
        userDialogRef.value.open(row);
    });
};
/* 高级检索 */
const openSearch = ref(false);
const handleAdvanceSearch = () => {
    openSearch.value = true;
};
// 表格头部--预约随访
const handleFollow = () => {
    nextTick(() => {
        calendarRef.value.open(2);
    });
};
/* 其他定制数据 */
const handleCustomData = () => {
    router.push({
        path: '/trial/customData',
        query: {},
    });
};
/*
查看样本 */
const handleViewSample = row => {
    sampleDialog.value = true;
};
let appointmentRef = ref(null);
/* 预约 */
const handleAppointment = row => {
    appointmentDialog.value = true;
    nextTick(() => {
        appointmentRef.value.open(row);
    });
};
/*
删除
 */
const rowDel = row => {
    ElMessageBox.confirm('确定将选择数据删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return remove(row.id);
        })
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
        });
};
let endDialogVal = ref({});
/* 结束 */
const handleEnd = row => {
    tableData.value = [row];
    endDialogVal.value = row;
    endDialog.value = true;
    signRef.value.clear();
};
// 结束弹窗结束按钮点击
const handleOver = () => {
    let completedSign = signRef.value.submit(80, 50);
    let form = {
        id: endDialogVal.value.id,
        completedSign: completedSign,
    };
    // putFileBase64(form).then((res) => {
    //   console.log('res', res);
    // })
    completed(form).then(res => {
        onLoad(page.value);
        ElMessage.success('操作成功!');
        endDialog.value = false;
    });
};
/* 评论 */
const handleComment = row => {
    let dialogForm = $DialogForm(appContext)({
        title: '病例评论',
        width: '30%',
        data: row,
        menuPosition: 'right',
        option: optionComment.value,
        beforeClose: done => {
            done();
        },
        callback: res => {
            res.data.id = row.id;
            initUpdate(res.data, res.done(), res.close());
        },
    });
    //dialogForm.close()
};
/* 备注 */
const handleRemark = row => {
    let dialogForm = $DialogForm(appContext)({
        title: '病例备注',
        width: '30%',
        data: row,
        menuPosition: 'right',
        option: optionRemark.value,
        beforeClose: done => {
            done();
        },
        callback: res => {
            res.data.id = row.id;
            initUpdate(res.data, res.done(), res.close());
        },
    });
};
const initUpdate = (row, done, close) => {
    update(row).then(
        () => {
            // onLoad(page.value);
            TabRefreshChange();
            ElMessage({
                type: 'success',
                message: '操作成功!',
            });
            done();
            close();
        },
        error => {
            done();
            console.log(error);
        }
    );
};
/* 起始标识 */
const handleSign = row => {
    let dialogForm = $DialogForm(appContext)({
        title: '起始标识',
        width: '30%',
        data: { title1: '下一个病例标识将从此标识开始取值范围：121~99999' },
        menuPosition: 'right',
        option: optionSign.value,
        beforeClose: done => {
            done();
        },
        callback: res => {
            console.log(res.data);

            setTimeout(() => {
                res.done();
                setTimeout(() => {
                    res.close();
                }, 1000);
            }, 1000);
        },
    });
};
// 新建病例，子页面点击“添加新病例”按钮，返回方法
const changeAddNewCase = (groupId) => {
    sendAddNewCaseObj.value = { groupId };
    crud.value.rowAdd();
    isBringIntoDialog.value = false;
};
onMounted(() => {
    if (routerQuery.value.trialId) {
        initEnrollmentStatistics(routerQuery.value.trialId);
    }
    getTrialStatus.value = '2';
    initTrialDetail(routerQuery.value.trialId);
});
const initTrialDetail = id => {
    if (id) {
        getTrialDetail(id).then(res => {
            getTrialStatus.value = res.data.data.status;
        });
    }
};
let enrollmentStatisticsVal = ref({});
const initEnrollmentStatistics = trialId => {
    enrollmentStatistics(trialId).then(res => {
        enrollmentStatisticsVal.value = res.data.data;
    });
};
const rowSave = (row, done, loading) => {
    delete row.timeLists;
    delete row.birthdays;
    row.trial = routerQuery.value.trialId;
    row.groupId = sendAddNewCaseObj.value.groupId || '';

    add(row)
        .then(() => {
            onLoad(page.value);
            ElMessage.success('操作成功!');
            done();
        })
        .catch(error => {
            loading();
            window.console.console.log(error);
        });
};
const rowUpdate = (row, index, done, loading) => {
    delete row.timeLists;
    delete row.birthdays;
    update(row).then(
        () => {
            // onLoad(page.value);
            TabRefreshChange();
            ElMessage({
                type: 'success',
                message: '操作成功!',
            });
            done();
        },
        error => {
            loading();
            console.log(error);
        }
    );
};
const searchReset = () => {
    query.value = {};
    TabRefreshChange();
    // onLoad(page.value, query.value);
};
const searchChange = (params, done) => {
    if (params.birthdays instanceof Array) {
        params.birthday = params.birthdays.join(',');
        delete params.birthdays;
    }
    if (params.timeLists instanceof Array) {
        params.timeLists = params.timeLists.join(',');
    }
    console.log(params);
    query.value = params;
    page.value.currentPage = 1;
    TabRefreshChange();
    // onLoad(page.value, params);
    done();
};
const beforeOpen = (done, type) => {
    if (['edit', 'view'].includes(type)) {
        getDetail(bringIntoForm.value.id).then(res => {
            bringIntoForm.value = res.data.data;
        });
    }
    done();
};
const selectionChange = list => {
    selectionList.value = list;
};
const selectionClear = () => {
    selectionList.value = [];
    crud.value.toggleSelection();
};
const currentChange = currentPage => {
    page.value.currentPage = currentPage;
    TabRefreshChange();
};
const sizeChange = pageSize => {
    page.value.pageSize = pageSize;
    TabRefreshChange();
};
const refreshChange = () => {
    onLoad(page.value, query.value);
};
const TabRefreshChange = () => {
    // if (selectTab.value === 1) {
    //   query.value.publicShare = '1';
    // } else if (selectTab.value === 2) {
    //   query.value.deptShare = '1';
    // }
    // if (selectTab.value === 3) {
    //   query.value.create_user = userInfo.value.user_id;
    // }
    onLoad(page.value, query.value);
};
const onLoad = (page, params = {}) => {
    loading.value = true;

    const { name, lbType } = query.value;

    let values = {
        name_: name,
        lbType_: lbType,
        descs: 'create_time',
        trial: routerQuery.value.trialId,
        ...params,
    };

    getList(page.currentPage, page.pageSize, values).then(res => {
        const DATA = res.data.data;
        page.total = DATA.total;
        data.value = DATA.records;
        data.value.forEach(item => {
            item.isShareSelect = 3;
            if (item.publicShare == '1') {
                item.isShareBtn = '0';
                item.isShareSelect = 1;
            } else if (item.deptShare == '1') {
                item.isShareBtn = '6';
                item.isShareSelect = 2;
            }
        });
        loading.value = false;
        selectionClear();
    });
};
/* 脱落操作 */
const handleFall = row => {
    optionFall.value.submitBtn = true;
    let dialogForm = $DialogForm(appContext)({
        title: '脱落操作',
        width: '30%',
        menuPosition: 'right',
        option: optionFall.value,
        beforeClose: done => {
            done();
        },
        callback: res => {
            console.log(res.data, row);
            let form = {
                ...res.data,
                id: row.id,
            };
            fallOff(form.id, form.fallOffRemark, form.fallOffSign).then(() => {
                ElMessage({
                    type: 'success',
                    message: '操作成功!',
                });
                onLoad(page.value);
                res.done();
                res.close()
            });
        },
    });
};
// 脱落原因
const handleFallDetail = row => {
    optionFall.value.submitBtn = false;
    let dialogForm = $DialogForm(appContext)({
        title: '脱落原因',
        width: '30%',
        menuPosition: 'right',
        option: optionFall.value,
        data: row,
        beforeClose: done => {
            done();
        },
    });
};
/* 锁定 */
const handleSock = (type, row) => {
    let title = type === 1 ? '您确定要锁定此病例？' : '您确定要恢复此病例？';
    let types = type === 1 ? '2' : '1';
    let form = {
        id: row.id,
        status: types
    }
    ElMessageBox.confirm(title, '提 示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        update(form).then(() => {
            TabRefreshChange();
            ElMessage({
                type: 'success',
                message: '操作成功!',
            });
        });
    });
};
const rowStyle = ({ row, column, rowIndex }) => {
    if (row.status == '4') {
        return { backgroundColor: '#d8ecd5' };
    } else if (row.status == '3') {
        return { backgroundColor: '#f6e6e6' };
    } else if (row.status == '2') {
        return { backgroundColor: '#eaeabf' };
    }
    return {};
};
// 进入入组采集
const handlePresentCrf = (row) => {
    router.push({
        path: '/trial/gather',
        query: {
            selectTab: 4,
            trialId: routerQuery.value.trialId,
            groupId: row.groupId,
            clinicalCaseId: row.id,
            clinicalCaseType: '9', //9代表入组采集 8纳排CRF
        },
    });
};
let isCutName = ref(false);
// 姓名切换
const cutName = () => {
    isCutName.value = !isCutName.value;
}


</script>

<style scoped lang="scss">
.container {
    width: 90%;

    .stats {
        margin-bottom: 20px;
        font-size: 16px;
        color: #606266;
        font-weight: bold;
    }
}
</style>
